package com.zxl.live.tools.alert;

import android.app.AppOpsManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Binder;

import java.lang.reflect.Method;

/**
 * 功能： api<23的获取权限
 * 作者： caijun
 * 时间： 2017/3/1  10 : 52
 */
public class LowerAlertState implements AlertPermissionUtils.AlertState {

    @Override
    public boolean canAlert(Context context) {
        try {
            AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            Class managerClass = manager.getClass();
            Method method = managerClass.getDeclaredMethod("checkOp", int.class, int.class, String.class);
            int isAllowNum = (Integer) method.invoke(manager, 24, Binder.getCallingUid(), context.getPackageName());

            if (AppOpsManager.MODE_ALLOWED == isAllowNum) {
                return true;
            } else if (AppOpsManager.MODE_DEFAULT == isAllowNum) {
                if (context.checkCallingOrSelfPermission(android.Manifest.permission.SYSTEM_ALERT_WINDOW) == PackageManager
                        .PERMISSION_GRANTED) {
                    // if either of the permissions are granted, we will allow it
                    return true;
                }
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
